package com.leyou.item.service.service.impl;

import com.leyou.common.bean.Result;
import com.leyou.common.bean.ResultCode;
import com.leyou.common.util.IdWorker;
import com.leyou.item.service.config.UploadProperties;
import com.leyou.item.service.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author zqq
 * @ClassName UploadServiceImpl
 * @Description
 * @date 2020/3/16-10:04
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UploadProperties uploadProperties;

    @Override
    public Result<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 校验文件的类型
        String contentType = file.getContentType();
        if (!uploadProperties.getImagesType().contains(contentType)){
            // 文件类型不合法，直接返回null
            log.info("文件类型不合法：{}", originalFilename);
            return Result.newFailure(ResultCode.USER_UPLOAD_TYPE_FAIL);
        }
        String url = null;
        try {
            // 校验文件的内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                log.info("文件内容不合法：{}", originalFilename);
                return Result.newFailure(ResultCode.USER_UPLOAD_CONTENT_FAIL);
            }
            // 获取文件的后缀名
            String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //获取两位0到15的随机数，作为文件名，并以这两位数创建随机的文件名
            Random r = new Random();
            Integer num1 = r.nextInt(15);
            Integer num2 = r.nextInt(15);
            IdWorker idWorker = new IdWorker(num1,num2);
            String fileName = idWorker.nextId().toString();
            String savePath = num1+"/"+num2+"/"+fileName+suffixName;

            // 检测是否存在目录
            File dest = new File(uploadProperties.getImageUploadPath()+num1+"\\"+num2+"\\" +fileName+suffixName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 保存到服务器
            file.transferTo(dest);
            // 生成url地址，返回
            url =  uploadProperties.getWebshowPath() + savePath;
        } catch (IOException e) {
            log.info("服务器内部错误：{}", originalFilename);
            return Result.newFailure(ResultCode.S_SYSTEM_EXCEPTION);
        }
        return Result.newSuccess(url);
    }
}
